package cn.com.bob.messageboard.interceptor;

import cn.com.bob.messageboard.utils.JwtConstant;
import cn.com.bob.messageboard.utils.JwtTokenUtil;
import cn.com.bob.messageboard.utils.R;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * @Author Bob
 * @Version：1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        //请求头中不含token
        if(StringUtils.isBlank(token)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(R.error(2001,"未登录")));
            return false;
        }else if(!JwtTokenUtil.validateToken(token)){
            //token解析错误
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(R.error(2001,"登录信息错误")));
            return false;
        }
        //结果上面两个判断，说明此token有效
        //获取存放于redis中的jwt与传入的jwt比较
        Claims claims = JwtTokenUtil.parseToken(token);
        String userId = JwtTokenUtil.getValue(claims, JwtConstant.USER_INFO_ID);
        String jwt = redisTemplate.opsForValue().get(userId);
        if(!token.equals(jwt)){
            //说明客户端传来的jwt与redis中的jwt不相等
            //删除redis中的jwt
            redisTemplate.delete(userId);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(R.error(2001,"jwt错误")));
            return false;
        }
        return true;
    }
}
